/*
 * @Author: your name
 * @Date: 2022-03-23 10:09:03
 * @LastEditTime: 2022-05-02 10:03:48
 * @LastEditors: Please set LastEditors
 * @Description: tab选择标签
 * @FilePath: \blog-system-front\src\components\CategoryTreeSelect\CategoryTabSelect.js
 */
import {Card, Space, Tabs, Tag } from "antd";
import React from "react";
import NoData from "../../Pages/Article/writeArticle/noData";
import { CloseOutlined } from "@ant-design/icons";
const { TabPane } = Tabs;
export default function CategoryTabSelect(props) {
  const { category, addTag, tags, close } = props;

  /**
   * @description: 处理children 递归函数，将多层父子结构,转换为一层
   * @param {*} item 当前item
   * @param {*} tempArr
   * @return {*}
   */
  const handleChildren = (item, tempArr) => {
    category.filter((d) => {
      if (d.parentId === item.category_id) {
        const childrens = category.filter((c) => c.parentId === d.category_id);
        if (childrens.length !== 0) {
          tempArr.push(d);
          handleChildren(d, tempArr);
        } else {
          tempArr.push(d);
        }
      }
    });
    return tempArr;
  };
  const renderOption = () => {
    let tempArr = [];
    category.map((d) => {
      // 证明是父级
      if (d.isTopLevel === 1) {
        const children = [];
        handleChildren(d, []).forEach((d) => {
          children.push(d);
        });
        tempArr.push({
          ...d,
          children: children,
        });
      }
    });
    const selectStyle = {
      background: "#507999",
      color: "white",
    };
    return tempArr.map((parent) => {
      return (
        <TabPane tab={parent.category_name} key={parent.category_id}>
          {parent.children.map((d) => {
            const index = tags.findIndex(
              (item) => item.category_id === d.category_id
            );

            return (
              <Space>
                <Tag
                  color="#ebf2f7"
                  style={index !== -1 ? selectStyle : {}}
                  onClick={() => {
                    if (index === -1 && tags.length < 5) {
                      addTag(d);
                    }
                  }}
                >
                  {d.category_name}
                </Tag>
              </Space>
            );
          })}
        </TabPane>
      );
    });
  };
  return (
    <Card
      title="标签选择"

      headStyle={{ textAlign: "center", fontWeight: "bolder" }}
      extra={
        <>
          <a
            href="#"
            onClick={() => {
              close();
            }}
          >
            <CloseOutlined />
          </a>
        </>
      }
    >
      {category.length === 0 ? (
        <NoData addTag={addTag}></NoData>
      ) : (
        <Tabs
          tabPosition="left"
          style={{ height: "270px" }}
          size="small"
          tabBarGutter={5}
        >
          {renderOption()}
        </Tabs>
      )}

      <div className="selectTooltip">还可以选择{5 - tags.length}个标签</div>
    </Card>
  );
}
